package com.yuexi.domain.config.alipay;

import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.yuexi.domain.util.IOUtilsEx;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.io.IOException;

/**
 * @author jie
 * @date 2023/4/10 -11:26
 */
@Slf4j
@Configuration
public class AliPayConfig {

    private Environment env;

    public AliPayConfig(AliPayProperties aliPayProperties, Environment env) throws IOException {
        this.env = env;
        Factory.setOptions(getOptions(aliPayProperties));
    }

    private Config getOptions(AliPayProperties aliPayProperties) throws IOException {
        log.info("aliPayProperties" + JSON.toJSONString(aliPayProperties));

        String profile = env.getProperty("spring.profiles.active");
        Config config = new Config();
        config.protocol = aliPayProperties.getProtocol();
        config.gatewayHost = aliPayProperties.getGatewayHost();
        config.signType = "RSA2";

        config.appId = aliPayProperties.getAppId();

        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中

        String merchantPrivatePath = "dev".equals(profile) ? getClass()
                .getResource(aliPayProperties.getMerchantPrivatePath()).getPath()
                : aliPayProperties.getMerchantPrivatePath();

        log.info("merchantPrivatePath:" + merchantPrivatePath);
        String merchantPrivateKey = IOUtilsEx.readFileToString(merchantPrivatePath);
        if (StringUtils.isEmpty(merchantPrivateKey)) {
            throw new IllegalArgumentException("请配置私钥");
        }
        config.merchantPrivateKey = merchantPrivateKey;


        String alipayPublicKeyPath = "dev".equals(profile) ? getClass()
                .getResource(aliPayProperties.getAlipayPublicKeyPath()).getPath()
                : aliPayProperties.getAlipayPublicKeyPath();

        log.info("alipayPublicKeyPath:" + alipayPublicKeyPath);
        String alipayPublicKey = IOUtilsEx.readFileToString(alipayPublicKeyPath);
        if (StringUtils.isEmpty(alipayPublicKey)) {
            throw new IllegalArgumentException("请配置私钥");
        }
        config.alipayPublicKey = alipayPublicKey;

        //可设置异步通知接收服务地址（可选）
        config.notifyUrl = aliPayProperties.getNotifyUrl();

        log.info("config" + JSON.toJSONString(config));
        return config;
    }
}
